﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Yamfinder.Service;
using Yamfinder.Web.Models;

namespace Yamfinder.Web.Controllers
{
    public class ImportController : Controller
    {
        private readonly IImportService _importService;
        private readonly IDataTypeService _dataTypeService;

        public ImportController(IImportService importService, IDataTypeService dataTypeService)
        {
            _importService = importService;
            _dataTypeService = dataTypeService;
        }

        //
        // GET: /Import/

        public ActionResult Index()
        {
            return View();
        }

        //
        // POST: /Import/

        [HttpPost]
        public ActionResult Index(ImportFileModel model)
        {
            if (ModelState.IsValid)
            {
                //Process file
                var book = new ClosedXML.Excel.XLWorkbook(model.File.InputStream);

                //Build the data dic to send to the db
                var worksheet = book.Worksheets.Worksheet(1);
                var columns = worksheet.ColumnsUsed();
                var rowCount = worksheet.RowsUsed().Count();
                
                var dataDic = new Dictionary<string, List<string>>();

                foreach (var column in columns)
                {
                    var header = column.FirstCell().GetString();
                    var data = new List<string>();

                    for (int i = 2; i <= rowCount; i++)
                    {
                        data.Add(column.Cell(i).GetString());
                    }

                    dataDic.Add(header, data);
                }

                //store in the database, show the mappings table
                var guid = _importService.StoreImportData(dataDic);

                return RedirectToAction("Mappings", new {guid});
            }
            else
            {
                return View(model);
            }
        }

        //
        // GET: /Import/Mappings

        public ActionResult Mappings(Guid? guid)
        {
            if (!guid.HasValue)
                return RedirectToAction("Index", "Home"); //TODO: Redirect to error page

            var columns = _importService.GetAnalysedColumns(guid.Value);
            var existingFields = _dataTypeService.Search(new DataTypeSearchCriteria() {OnlyRequired = false});
            
            var model = new ImportMappingsModel(guid.Value, columns, existingFields);

            return View(model);
        }

        //
        // POST: /Import/Mappings

        [HttpPost]
        public ActionResult Mappings(ImportMappingsModel model)
        {
            if (ModelState.IsValid)
            {
                //convert to service mappings
                var serviceMappings = model.Mappings.Select(mapping => new ImportMapping()
                                                {
                                                    DatabaseName = mapping.DatabaseName,
                                                    ImportName = mapping.ImportName,
                                                    Type = mapping.Type
                                                }).ToList();

                //tell the database to finish the import
                var rows = _importService.SaveUsingMappings(model.Id, serviceMappings);

                //Get result of process
                return View("ImportSuccessful", new ImportSuccessfulModel() { RowsImported = rows });
            }

            return View(model);

            
        }
    }
}
